package org.teremail.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.HTMLTable;
import com.google.gwt.user.client.ui.SourcesTableEvents;
import com.google.gwt.user.client.ui.TableListener;

public class TableSelectionListener implements TableListener, ClickHandler {
    
    public final static String SELECTED_STYLE = "selected";
    private static final int UNSELECTED = -1;
    private final HTMLTable view;
    private final int[] exclude;
    private int selected = UNSELECTED;

    public TableSelectionListener(HTMLTable ft, int[] exclude) {
        this.view = ft;
        this.exclude = new int[exclude.length];
        for (int i = 0; i < exclude.length; i++) {
            this.exclude[i] = exclude[i];
        }
    }

    public void onCellClicked(SourcesTableEvents sender, int row, int cell) {
        if (!isExcluded(row)) {
            if (selected != -1) {
                view.getRowFormatter().removeStyleName(selected, SELECTED_STYLE);
            }
            selected = row;
            if (row < view.getRowCount()) {
                view.getRowFormatter().addStyleName(selected, SELECTED_STYLE);
            }
        }
    }
    
    @Override
    public void onClick(ClickEvent clickEvent) {
    }
    
    private boolean isExcluded(int row) {
        for (int i = 0; i < exclude.length; i++) {
            if (exclude[i] == row) {
                return true;
            }
        }
        return false;
    }

    public static TableSelectionListener create(HTMLTable ft, int[] exclude) {
        return new TableSelectionListener(ft, exclude);
    }
}
